package cn.kent.high.juc.lock.reentrantLock;


import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;

public class NonReentrantLockTest {
    static final NonReentrantLock lock = new NonReentrantLock();
    static final Condition notFull = lock.newCondition();
    static final Condition notEmpty = lock.newCondition();

    final static Queue<String> queue = new LinkedBlockingQueue<String>();
    final static int queueSize = 10;

    public static void main(String[] args) {

        Thread producer = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    // 队列满了，等待
                    while (queue.size() == queueSize) {
                        notEmpty.await();
                    }
                    // 添加元素到队列
                    queue.add("ele");
                    // 唤醒消费线程
                    notFull.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    // 队列为空则等待
                    while (queue.size() == 0) {
                        notFull.await();
                    }
                    // 消费一个元素
                    Object ele = queue.poll();
                    // 唤醒生产者线程
                    notEmpty.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        producer.start();
        consumer.start();

    }
}
